/*
    File:       AirPlayReceiverPOSIX.c
    Package:    Apple CarPlay Communication Plug-in.
    Abstract:   n/a
    Version:    450.14

    Disclaimer: IMPORTANT: This Apple software is supplied to you, by Apple Inc. ("Apple"), in your
    capacity as a current, and in good standing, Licensee in the MFi Licensing Program. Use of this
    Apple software is governed by and subject to the terms and conditions of your MFi License,
    including, but not limited to, the restrictions specified in the provision entitled ”Public
    Software”, and is further subject to your agreement to the following additional terms, and your
    agreement that the use, installation, modification or redistribution of this Apple software
    constitutes acceptance of these additional terms. If you do not agree with these additional terms,
    please do not use, install, modify or redistribute this Apple software.

    Subject to all of these terms and in consideration of your agreement to abide by them, Apple grants
    you, for as long as you are a current and in good-standing MFi Licensee, a personal, non-exclusive
    license, under Apple's copyrights in this original Apple software (the "Apple Software"), to use,
    reproduce, and modify the Apple Software in source form, and to use, reproduce, modify, and
    redistribute the Apple Software, with or without modifications, in binary form. While you may not
    redistribute the Apple Software in source form, should you redistribute the Apple Software in binary
    form, you must retain this notice and the following text and disclaimers in all such redistributions
    of the Apple Software. Neither the name, trademarks, service marks, or logos of Apple Inc. may be
    used to endorse or promote products derived from the Apple Software without specific prior written
    permission from Apple. Except as expressly stated in this notice, no other rights or licenses,
    express or implied, are granted by Apple herein, including but not limited to any patent rights that
    may be infringed by your derivative works or by other works in which the Apple Software may be
    incorporated.

    Unless you explicitly state otherwise, if you provide any ideas, suggestions, recommendations, bug
    fixes or enhancements to Apple in connection with this software (“Feedback”), you hereby grant to
    Apple a non-exclusive, fully paid-up, perpetual, irrevocable, worldwide license to make, use,
    reproduce, incorporate, modify, display, perform, sell, make or have made derivative works of,
    distribute (directly or indirectly) and sublicense, such Feedback in connection with Apple products
    and services. Providing this Feedback is voluntary, but if you do provide Feedback to Apple, you
    acknowledge and agree that Apple may exercise the license granted above without the payment of
    royalties or further consideration to Participant.

    The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO WARRANTIES, EXPRESS OR
    IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY
    AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR
    IN COMBINATION WITH YOUR PRODUCTS.

    IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR CONSEQUENTIAL DAMAGES
    (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
    PROFITS; OR BUSINESS INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION
    AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT
    (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE
    POSSIBILITY OF SUCH DAMAGE.

    Copyright (C) 2013-2020 Apple Inc. All Rights Reserved. Not to be used or disclosed without permission from Apple.

    POSIX platform plugin for AirPlay.
*/

#include "AudioUtils.h"

#include "AirPlayCommon.h"
#include "AirPlayReceiverServer.h"
#include "AirPlayReceiverServerPriv.h"
#include "AirPlayReceiverSession.h"
#include "AirPlayReceiverSessionPriv.h"
#include "ScreenUtils.h"

#if 0
#pragma mark == Structures ==
#endif

//===========================================================================================================================
//  Structures
//===========================================================================================================================

// AirPlayReceiverServerPlatformData

typedef struct {
    uint32_t                        systemBufferSizeMicros;
    uint32_t                        systemSampleRate;

}   AirPlayReceiverServerPlatformData;

// AirPlayReceiverSessionPlatformData

typedef struct {
    AirPlayReceiverSessionRef               session;
    AirPlayAudioStreamPlatformContext       mainAudioCtx;
    AirPlayAudioStreamPlatformContext       altAudioCtx;
    Boolean                                 sessionStarted;

}   AirPlayReceiverSessionPlatformData;

#if 0
#pragma mark == Globals ==
#endif

//===========================================================================================================================
//  Globals
//===========================================================================================================================

ulog_define(AirPlayReceiverPlatform, kLogLevelTrace, kLogFlags_Default, "AirPlayReceiverPOSIX",  NULL);
#define atrp_ucat()                 &log_category_from_name( AirPlayReceiverPlatform )
#define atrp_ulog( LEVEL, ... )     ulog( atrp_ucat(), (LEVEL), __VA_ARGS__ )

#if 0
#pragma mark -
#pragma mark == Server-level APIs ==
#endif

//===========================================================================================================================
//  AirPlayReceiverServerPlatformInitialize
//===========================================================================================================================

OSStatus    AirPlayReceiverServerPlatformInitialize(AirPlayReceiverServerRef inServer) {
    OSStatus                                err;
    AirPlayReceiverServerPlatformData*      platform;

    platform = (AirPlayReceiverServerPlatformData*) calloc(1, sizeof(*platform));
    require_action(platform, exit, err = kNoMemoryErr);
    inServer->platformPtr = platform;
    err = kNoErr;

exit:
    return (err);
}

//===========================================================================================================================
//  AirPlayReceiverServerPlatformFinalize
//===========================================================================================================================

void    AirPlayReceiverServerPlatformFinalize(AirPlayReceiverServerRef inServer) {
    AirPlayReceiverServerPlatformData* const   platform = (AirPlayReceiverServerPlatformData*) inServer->platformPtr;

    if (!platform) {
        return;
    }

    free(platform);
    inServer->platformPtr = NULL;
}

//===========================================================================================================================
//  AirPlayReceiverServerPlatformControl
//===========================================================================================================================

OSStatus
AirPlayReceiverServerPlatformControl(
    CFTypeRef           inServer,
    uint32_t            inFlags,
    CFStringRef         inCommand,
    CFTypeRef           inQualifier,
    CFDictionaryRef     inParams,
    CFDictionaryRef*    outParams) {
    AirPlayReceiverServerRef const              server      = (AirPlayReceiverServerRef) inServer;
    OSStatus                                    err;

    (void) inFlags;

    if (0) {}

    // Other

    else if (server->delegate.control_f) {
        err = server->delegate.control_f(server, inCommand, inQualifier, inParams, outParams, server->delegate.context);
        goto exit;
    }
    else {
        err = kNotHandledErr;
        goto exit;
    }
    err = kNoErr;

exit:
    return (err);
}

//===========================================================================================================================
//  AirPlayReceiverServerPlatformCopyProperty
//===========================================================================================================================

CFTypeRef
AirPlayReceiverServerPlatformCopyProperty(
    CFTypeRef   inServer,
    uint32_t    inFlags,
    CFStringRef inProperty,
    CFTypeRef   inQualifier,
    OSStatus*   outErr) {
    AirPlayReceiverServerRef const      server = (AirPlayReceiverServerRef) inServer;
    CFTypeRef                           value  = NULL;
    OSStatus                            err;

    (void) inFlags;

    if (0) {}

    // SystemFlags

    else if (CFEqual(inProperty, CFSTR(kAirPlayProperty_StatusFlags))) {
        // Always report an audio link until we can detect it correctly.

        value = CFNumberCreateInt64(kAirPlayStatusFlag_AudioLink);
        require_action(value, exit, err = kUnknownErr);
    }

    // Other

    else if (server->delegate.copyProperty_f) {
        value = server->delegate.copyProperty_f(server, inProperty, inQualifier, &err, server->delegate.context);
        goto exit;
    }
    else {
        err = kNotHandledErr;
        goto exit;
    }
    err = kNoErr;

exit:
    if (err) {
        ForgetCF(&value);
    }
    if (outErr) {
        *outErr = err;
    }
    return (value);
}

//===========================================================================================================================
//  AirPlayReceiverServerPlatformSetProperty
//===========================================================================================================================

OSStatus
AirPlayReceiverServerPlatformSetProperty(
    CFTypeRef   inServer,
    uint32_t    inFlags,
    CFStringRef inProperty,
    CFTypeRef   inQualifier,
    CFTypeRef   inValue) {
    AirPlayReceiverServerRef const      server = (AirPlayReceiverServerRef) inServer;
    OSStatus                            err;

    (void) inFlags;

    if (0) {}

    // Other

    else if (server->delegate.setProperty_f) {
        err = server->delegate.setProperty_f(server, inProperty, inQualifier, inValue, server->delegate.context);
        goto exit;
    }
    else {
        err = kNotHandledErr;
        goto exit;
    }
    err = kNoErr;

exit:
    return (err);
}

#if 0
#pragma mark -
#pragma mark == Session-level APIs ==
#endif

//===========================================================================================================================
//  AirPlayReceiverSessionPlatformInitialize
//===========================================================================================================================

OSStatus    AirPlayReceiverSessionPlatformInitialize(AirPlayReceiverSessionRef inSession) {
    OSStatus                                    err;
    AirPlayReceiverSessionPlatformData*         spd;

    spd = (AirPlayReceiverSessionPlatformData*) calloc(1, sizeof(*spd));
    require_action(spd, exit, err = kNoMemoryErr);
    spd->session = inSession;
    inSession->platformPtr = spd;
    err = kNoErr;

exit:
    return (err);
}

//===========================================================================================================================
//  AirPlayReceiverSessionPlatformFinalize
//===========================================================================================================================

void    AirPlayReceiverSessionPlatformFinalize(AirPlayReceiverSessionRef inSession) {
    AirPlayReceiverSessionPlatformData* const      spd = (AirPlayReceiverSessionPlatformData*) inSession->platformPtr;

    if (!spd) {
        return;
    }

    spd->sessionStarted = false;

    free(spd);
    inSession->platformPtr = NULL;
}

//===========================================================================================================================
//  AirPlayReceiverSessionPlatformControl
//===========================================================================================================================

OSStatus
AirPlayReceiverSessionPlatformControl(
    CFTypeRef           inSession,
    uint32_t            inFlags,
    CFStringRef         inCommand,
    CFTypeRef           inQualifier,
    CFDictionaryRef     inParams,
    CFDictionaryRef*    outParams) {
    AirPlayReceiverSessionRef const                 session = (AirPlayReceiverSessionRef) inSession;
    AirPlayReceiverSessionPlatformData* const      spd = (AirPlayReceiverSessionPlatformData*) session->platformPtr;
    OSStatus                                        err;
    double                                          duration, finalVolume;

    (void) inFlags;
    atrp_ulog(kLogLevelNotice, "### AirPlayReceiverSessionPlatformControl inCommand = %@ \n", inCommand);
    if (0) {}

    // DuckAudio

    else if (CFEqual(inCommand, CFSTR(kAirPlayCommand_DuckAudio))) {
        duration = CFDictionaryGetDouble(inParams, CFSTR(kAirPlayKey_DurationMs), &err);
        if (err || (duration < 0)) {
            duration = 500;
        }
        duration /= 1000;

        finalVolume = CFDictionaryGetDouble(inParams, CFSTR(kAirPlayProperty_Volume), &err);
        finalVolume = !err ? DBtoLinear((float) finalVolume) : 0.2;
        finalVolume = Clamp(finalVolume, 0.0, 1.0);

        // Notify client of duck command
        if (session->delegate.duckAudio_f) {
            atrp_ulog(kLogLevelNotice, "Delegating ducking of audio to %f within %f seconds\n", finalVolume, duration);
            session->delegate.duckAudio_f(session, duration, finalVolume, session->delegate.context);
        }
    }

    // UnduckAudio

    else if (CFEqual(inCommand, CFSTR(kAirPlayCommand_UnduckAudio))) {
        duration = CFDictionaryGetDouble(inParams, CFSTR(kAirPlayKey_DurationMs), &err);
        if (err || (duration < 0)) {
            duration = 500;
        }
        duration /= 1000;

        // Notify client of unduck command
        if (session->delegate.unduckAudio_f) {
            atrp_ulog(kLogLevelNotice, "Delegating unducking of audio within %f seconds\n", duration);
            session->delegate.unduckAudio_f(session, duration, session->delegate.context);
        }
    }

    // StartSession

    else if (CFEqual(inCommand, CFSTR(kAirPlayCommand_StartSession))) {
        spd->sessionStarted = true;
    }

    // Perform feedback
    else if (CFEqual(inCommand, CFSTR(kAirPlayCommand_PerformHapticFeedback))) {
        if (session->delegate.performHapticFeedback_f) {
            AirPlayHapticFeedbackType hapticFeedbackType = CFDictionaryGetUInt64(inParams, CFSTR(kAirPlayKey_HapticFeedbackType),
                                                                                 &err);
            require_noerr(err, exit);

            uint32_t deviceUID = 0;
            char deviceUIDCString[8];

            CFDictionaryGetCString(inParams, CFSTR(kAirPlayKey_UUID), deviceUIDCString, sizeof(deviceUIDCString), &err);
            require_noerr(err, exit);

            deviceUID = (uint32_t)strtoul(deviceUIDCString, NULL, 16);

            require_noerr(err, exit);
            session->delegate.performHapticFeedback_f(session, hapticFeedbackType, deviceUID, session->delegate.context);
        }
    }
    else if (CFEqual(inCommand, CFSTR(kAirPlayCommand_DeviceOfferFocus))) {
        if (session->delegate.attemptFocusChange_f) {
            AirPlayFocusChange focusChange = {0};

            focusChange.originX = CFDictionaryGetUInt32(inParams, CFSTR(kAirPlayKey_OriginXPixels), &err);
            require_noerr(err, exit);
            focusChange.originY = CFDictionaryGetUInt32(inParams, CFSTR(kAirPlayKey_OriginYPixels), &err);
            require_noerr(err, exit);
            focusChange.width = CFDictionaryGetUInt32(inParams, CFSTR(kAirPlayKey_WidthPixels), &err);
            require_noerr(err, exit);
            focusChange.height = CFDictionaryGetUInt32(inParams, CFSTR(kAirPlayKey_HeightPixels), &err);
            require_noerr(err, exit);
            focusChange.heading = CFDictionaryGetUInt32(inParams, CFSTR(kAirPlayKey_FocusHeading), &err);
            require_noerr(err, exit);

            session->delegate.attemptFocusChange_f(session, focusChange, session->delegate.context);
        }
    }

    // Other

    else if (session->delegate.control_f) {
        err = session->delegate.control_f(session, inCommand, inQualifier, inParams, outParams, session->delegate.context);
        goto exit;
    }
    else {
        err = kNotHandledErr;
        goto exit;
    }
    err = kNoErr;

exit:
    return (err);
}

//===========================================================================================================================
//  AirPlayReceiverSessionPlatformCopyProperty
//===========================================================================================================================

CFTypeRef
AirPlayReceiverSessionPlatformCopyProperty(
    CFTypeRef   inSession,
    uint32_t    inFlags,
    CFStringRef inProperty,
    CFTypeRef   inQualifier,
    OSStatus*   outErr) {
    AirPlayReceiverSessionRef const                 session = (AirPlayReceiverSessionRef) inSession;
    AirPlayReceiverSessionPlatformData* const       spd     = (AirPlayReceiverSessionPlatformData*) session->platformPtr;
    OSStatus                                        err;
    CFTypeRef                                       value = NULL;

    (void) inFlags;
    (void) spd;

    if (session->delegate.copyProperty_f) {
        value = session->delegate.copyProperty_f(session, inProperty, inQualifier, &err, session->delegate.context);
    }
    else {
        err = kNotHandledErr;
    }

    if (outErr) {
        *outErr = err;
    }
    return (value);
}

//===========================================================================================================================
//  AirPlayReceiverSessionPlatformSetProperty
//===========================================================================================================================

OSStatus
AirPlayReceiverSessionPlatformSetProperty(
    CFTypeRef   inSession,
    uint32_t    inFlags,
    CFStringRef inProperty,
    CFTypeRef   inQualifier,
    CFTypeRef   inValue) {
    AirPlayReceiverSessionRef const                 session = (AirPlayReceiverSessionRef) inSession;
    AirPlayReceiverSessionPlatformData* const      spd     = (AirPlayReceiverSessionPlatformData*) session->platformPtr;
    OSStatus                                        err;

    (void) spd;
    (void) inFlags;

    if (0) {}

    // Other

    else if (session->delegate.setProperty_f) {
        err = session->delegate.setProperty_f(session, inProperty, inQualifier, inValue, session->delegate.context);
        goto exit;
    }
    else {
        err = kNotHandledErr;
        goto exit;
    }
    err = kNoErr;

exit:
    return (err);
}

#if 0
#pragma mark -
#endif

